<template>
  <MdEditor
    v-if="currentUserRole === ROLE_ENUM.ADMIN"
    :value="announcementData.content"
    :upload-images="uploadImages"
    :handle-change="onContentChange"
  />
  <div v-if="currentUserRole === ROLE_ENUM.ADMIN" class="submitContent">
    <a-button
      style="width: 160px"
      type="primary"
      status="success"
      @click="saveAnnouncement()"
    >
      发布
    </a-button>
  </div>
  <MdViewer v-else :value="announcementData.content" />
</template>

<script lang="ts" setup>
import MdEditor from "@/components/MdEditor.vue";
import { useStore } from "vuex";
import { onMounted, ref } from "vue";
import ROLE_ENUM from "@/access/ROLE_ENUM";
import MdViewer from "@/components/MdViewer.vue";
import { Message } from "@arco-design/web-vue";
import { AnnouncementControllerService } from "../../generated";
import axios from "axios";
import {baseUrl} from "@/plugins/axios";

const store = useStore();

// 公告数据
const announcementData = ref({
  id: "",
  content: "",
});

// 当前登录用户角色
const currentUserRole = store.state.user.loginUser?.userRole;

/**
 * 在内容改变时触发
 * @param value 内容
 */
const onContentChange = (value: string) => {
  announcementData.value.content = value;
};

/**
 * 获取公告
 */
const getAnnouncement = async () => {
  const res = await AnnouncementControllerService.getAnnouncementUsingGet();
  if (res.code === 0) {
    announcementData.value = res.data?.length == 0 ? {} : (res.data![0] as any);
  } else {
    Message.error("获取公告失败，" + res.message);
  }
};

/**
 * 发布公告
 */
const saveAnnouncement = async () => {
  const res = await AnnouncementControllerService.saveAnnouncementUsingPost(
    announcementData.value as any
  );
  if (res.code === 0) {
    Message.success("公告发布成功");
  } else {
    Message.error("公告发布失败， " + res.message);
  }
};

/**
 * 上传图片
 * @param file 图片文件
 */
const uploadImages = async (file: any) => {
  const formData = new FormData();
  formData.append("file", file[0]);

  const res = await axios.post(baseUrl + "/api/file/upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
  if (res.data.code === 0) {
    return [{ url: res.data.data }];
  } else {
    Message.error("上传图片失败，" + res.data.message);
    return [{ url: "" }];
  }
};

onMounted(() => {
  getAnnouncement();
});
</script>

<style scoped>
/*使用flex布局，让button位于最后*/
.submitContent {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

:deep(.bytemd) {
  height: 77vh;
}
</style>
